#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于真实信息创建HAI实例
参考: https://github.com/Rsers/HAI-remote
"""

import os
import sys
import json
import time
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def create_real_hai_instance():
    """创建真实的HAI实例"""
    print("🏗️ 创建真实HAI实例")
    print("=" * 50)
    print("参考项目: https://github.com/Rsers/HAI-remote")
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 基于真实信息设置参数
        req = models.RunInstancesRequest()
        
        # 使用真实的应用ID
        req.ApplicationId = "app-oefac6i2"  # GFPGAN API
        req.InstanceName = "real-hai-instance-" + str(int(time.time()))
        req.InstanceCount = 1
        
        # 基于截图信息，尝试GPU基础型对应的BundleType
        # 从HAI-remote项目看，成功案例使用了Tesla T4 16GB
        bundle_types_to_try = [
            "HAI_BASIC",           # 基础型
            "HAI_BASIC_16GB",      # 基础型16GB
            "HAI_GPU_BASIC",       # GPU基础型
            "HAI_GPU_BASIC_16GB",  # GPU基础型16GB
            "HAI_T4_16GB",         # T4 16GB
            "HAI_T4_BASIC",        # T4基础型
            "HAI_BASIC_T4",        # 基础型T4
            "HAI_STANDARD",        # 标准型
            "HAI_PERFORMANCE",     # 性能型
            "HAI_PREMIUM"          # 高级型
        ]
        
        print(f"📋 实例创建参数:")
        print(f"  ApplicationId: {req.ApplicationId}")
        print(f"  InstanceName: {req.InstanceName}")
        print(f"  InstanceCount: {req.InstanceCount}")
        print(f"  地域: ap-beijing")
        
        # 设置系统盘 - 基于截图使用80GB
        system_disk = models.SystemDisk()
        system_disk.DiskType = "CLOUD_PREMIUM"
        system_disk.DiskSize = 80  # 使用截图中的80GB
        req.SystemDisk = system_disk
        
        print(f"  SystemDisk.Type: {system_disk.DiskType}")
        print(f"  SystemDisk.Size: {system_disk.DiskSize}GB")
        
        # 尝试不同的BundleType
        for bundle_type in bundle_types_to_try:
            try:
                print(f"\n🧪 尝试BundleType: {bundle_type}")
                req.BundleType = bundle_type
                
                # 执行创建实例
                print(f"🚀 开始创建实例...")
                resp = client.RunInstances(req)
                
                print(f"✅ 实例创建成功!")
                print(f"请求ID: {resp.RequestId}")
                
                if hasattr(resp, 'InstanceIdSet') and resp.InstanceIdSet:
                    instance_ids = resp.InstanceIdSet
                    print(f"实例ID列表: {instance_ids}")
                    
                    for instance_id in instance_ids:
                        print(f"\n📊 实例详情:")
                        print(f"  实例ID: {instance_id}")
                        print(f"  应用ID: {req.ApplicationId}")
                        print(f"  实例名称: {req.InstanceName}")
                        print(f"  BundleType: {bundle_type}")
                        print(f"  地域: ap-beijing")
                        print(f"  系统盘: {system_disk.DiskSize}GB {system_disk.DiskType}")
                        
                        # 查询实例状态
                        print(f"\n🔍 查询实例状态...")
                        try:
                            status_req = models.DescribeInstancesRequest()
                            status_req.InstanceIds = [instance_id]
                            status_resp = client.DescribeInstances(status_req)
                            
                            if status_resp.InstanceSet:
                                instance_info = status_resp.InstanceSet[0]
                                print(f"  实例状态: {instance_info.InstanceState}")
                                print(f"  创建时间: {instance_info.CreatedTime}")
                                
                                # 获取更多实例信息
                                if hasattr(instance_info, 'PublicIpAddresses') and instance_info.PublicIpAddresses:
                                    print(f"  公网IP: {instance_info.PublicIpAddresses[0]}")
                                if hasattr(instance_info, 'PrivateIpAddresses') and instance_info.PrivateIpAddresses:
                                    print(f"  内网IP: {instance_info.PrivateIpAddresses[0]}")
                                
                        except Exception as e:
                            print(f"  状态查询失败: {e}")
                        
                        # 根据HAI-remote项目经验，实例创建需要10-20分钟
                        print(f"\n⏰ 重要提醒:")
                        print(f"  根据HAI-remote项目经验:")
                        print(f"  - 实例创建需要10-20分钟")
                        print(f"  - 创建期间不计费")
                        print(f"  - 建议使用监控工具跟踪状态")
                        
                        return instance_id
                else:
                    print("❌ 未返回实例ID")
                    continue
                    
            except Exception as e:
                error_msg = str(e)
                print(f"❌ BundleType {bundle_type} 失败: {error_msg}")
                
                # 分析错误信息
                if "BundleTypeNotFound" in error_msg:
                    print(f"  💡 BundleType不存在，尝试下一个")
                elif "Permission" in error_msg or "权限" in error_msg:
                    print(f"  💡 权限不足")
                    break
                elif "Quota" in error_msg or "配额" in error_msg:
                    print(f"  💡 配额不足")
                    break
                else:
                    print(f"  💡 其他错误，继续尝试")
                continue
        
        print(f"\n❌ 所有BundleType都失败")
        return None
            
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def monitor_instance_creation(instance_id):
    """监控实例创建状态"""
    print(f"\n🔍 监控实例创建状态: {instance_id}")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        # 监控实例状态
        max_attempts = 20  # 最多监控20分钟
        attempt = 0
        
        while attempt < max_attempts:
            try:
                req = models.DescribeInstancesRequest()
                req.InstanceIds = [instance_id]
                resp = client.DescribeInstances(req)
                
                if resp.InstanceSet:
                    instance = resp.InstanceSet[0]
                    state = instance.InstanceState
                    
                    print(f"  第{attempt + 1}次检查: {state}")
                    
                    if state == "RUNNING":
                        print(f"✅ 实例创建完成！")
                        if hasattr(instance, 'PublicIpAddresses') and instance.PublicIpAddresses:
                            print(f"  公网IP: {instance.PublicIpAddresses[0]}")
                        if hasattr(instance, 'PrivateIpAddresses') and instance.PrivateIpAddresses:
                            print(f"  内网IP: {instance.PrivateIpAddresses[0]}")
                        return True
                    elif state in ["PENDING", "STARTING"]:
                        print(f"  ⏳ 实例创建中，等待1分钟后重试...")
                        time.sleep(60)  # 等待1分钟
                        attempt += 1
                    else:
                        print(f"  ❌ 实例状态异常: {state}")
                        return False
                else:
                    print(f"  ❌ 实例不存在")
                    return False
                    
            except Exception as e:
                print(f"  ❌ 状态查询失败: {e}")
                time.sleep(60)
                attempt += 1
        
        print(f"  ⏰ 监控超时（20分钟），实例可能仍在创建中")
        return False
        
    except Exception as e:
        print(f"❌ 监控失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 创建真实HAI实例")
    print("=" * 60)
    print("参考项目: https://github.com/Rsers/HAI-remote")
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    
    # 创建真实实例
    instance_id = create_real_hai_instance()
    
    if instance_id:
        print(f"\n🎉 真实HAI实例创建成功！")
        print(f"\n📋 总结:")
        print(f"✅ 实例ID: {instance_id}")
        print(f"✅ 应用ID: app-oefac6i2")
        print(f"✅ 应用名称: GFPGAN API")
        print(f"✅ 地域: ap-beijing")
        print(f"✅ 系统盘: 80GB CLOUD_PREMIUM")
        
        # 开始监控实例创建
        print(f"\n🔍 开始监控实例创建状态...")
        if monitor_instance_creation(instance_id):
            print(f"\n🎉 实例创建完全成功！")
        else:
            print(f"\n⚠️ 实例可能仍在创建中，请稍后检查")
        
        print(f"\n🔗 后续操作:")
        print(f"- 可以在腾讯云控制台查看实例详情")
        print(f"- 可以通过API管理实例状态")
        print(f"- 可以部署应用和任务")
        print(f"- 参考HAI-remote项目进行自动化部署")
        
        return True
    else:
        print(f"\n❌ 真实实例创建失败")
        
        print(f"\n📋 需要的信息:")
        print(f"1. 正确的BundleType")
        print(f"2. 确认应用配置")
        print(f"3. 确认权限配置")
        print(f"4. 确认配额情况")
        
        print(f"\n💡 建议:")
        print(f"- 参考HAI-remote项目: https://github.com/Rsers/HAI-remote")
        print(f"- 在腾讯云控制台手动创建一个实例")
        print(f"- 查看实际使用的参数")
        print(f"- 联系腾讯云技术支持")
        
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
